package utils

import (
	"bufio"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"io"
	"os/exec"
)

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

//封装一个函数来执行命令
func ExecCommand(commandName string, params []string, cmdOut chan string) {

	//执行命令
	cmd := exec.Command(commandName, params...)

	//显示运行的命令
	fmt.Printf("执行命令：%s", cmd.Args)

	stdout, outErr := cmd.StdoutPipe()
	errReader, eErr := cmd.StderrPipe()

	if eErr != nil {
		cmdOut <- "eErr:" + eErr.Error()
	}

	//开启错误处理
	go handlerStdErr(errReader, cmdOut)

	if outErr != nil {
		cmdOut <- "outErr:" + outErr.Error()
		return
	}

	go handlerStdOut(stdout, cmdOut)

	cmd.Start()
	cmd.Wait()
}

//处理标准的输出
func handlerStdOut(stdout io.ReadCloser, stdOut chan string) {
	in := bufio.NewScanner(stdout)
	for in.Scan() {
		cmdRe := ConvertByte2String(in.Bytes(), "GB18030")
		stdOut <- cmdRe
	}
}

//处理错误的输出
func handlerStdErr(errReader io.ReadCloser, errOut chan string) {
	in := bufio.NewScanner(errReader)
	for in.Scan() {
		cmdRe := ConvertByte2String(in.Bytes(), GB18030)
		errOut <- "errOut:" + cmdRe
	}
}

//对字符进行转码
func ConvertByte2String(byte []byte, charset Charset) string {
	var str string
	switch charset {
	case GB18030:
		var decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}
	return str
}
